package com.cmf.myproject.service.task;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cmf.myproject.dal.mybatis.enums.TaskStatusEnum;
import com.cmf.myproject.dal.mybatis.filters.TaskQueryFilter;
import com.cmf.myproject.dal.mybatis.mapper.TaskMapper;
import com.cmf.myproject.dal.mybatis.mapper.UserMapper;
import com.cmf.myproject.dal.mybatis.model.Task;
import com.cmf.myproject.dal.mybatis.model.User;
import com.cmf.myproject.dal.mybatis.model.UserExample;
import com.cmf.myproject.dal.mybatis.mymapper.MyTaskMapper;
import com.cmf.myproject.dal.mybatis.mymodel.TaskProject;
import com.cmf.myproject.dal.mybatis.mymodel.WeeklyViewRspDto;
import com.cmf.myproject.service.task.dto.TaskAddItemReqDto;
import com.cmf.myproject.service.task.dto.TaskUpdateItemReqDto;
import com.cmf.myproject.util.dto.layui.SelectMRspDto;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.system.core.date.DateTimeConstant;
import com.system.core.results.ResultBase;
import com.system.core.view.layui.table.TableViewRspDto;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class TaskService {
	
	@Autowired
	private TaskMapper taskMapper;
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private MyTaskMapper myTaskMapper;
	
	public List<SelectMRspDto> taskStatusList(){
		List<SelectMRspDto> list = new ArrayList<SelectMRspDto>();
		for(TaskStatusEnum item:TaskStatusEnum.getAllEnum()) {
			SelectMRspDto dto = new SelectMRspDto();
			dto.setId(item.getCode());
			dto.setName(item.getMessage());
			dto.setStatus(1);
			list.add(dto);
		}
		return list;
	}
	
	/**
	 * 页面列表查询
	 * @return TableViewRspDto 返回TableViewRspDto视图对象，符合Layui规范
	 */
	public TableViewRspDto<TaskProject> taskList(TaskQueryFilter filter){
		log.debug("[task]查询入参：{}",filter);
		TableViewRspDto<TaskProject> pageResult = new TableViewRspDto<TaskProject>();
		if(StringUtils.isNotBlank(filter.getName())) {
			filter.setName("%"+filter.getName()+"%");
		}
		if(StringUtils.isNotBlank(filter.getCodeStartStrStart())) {
			filter.setCodeStartStrStart(filter.getCodeStartStrStart() + DateTimeConstant.TIME_OF_DAY_BEGIN);
		}
		if(StringUtils.isNotBlank(filter.getCodeEndStrEnd())) {
			filter.setCodeEndStrEnd(filter.getCodeEndStrEnd() + DateTimeConstant.TIME_OF_DAY_END);
		}
		Page<Task> page = PageHelper.startPage(filter.getPage(), filter.getLimit());
		pageResult.setData(myTaskMapper.selectByFilter(filter));
		pageResult.setCount(page.getTotal());
		pageResult.setCode(0);
		pageResult.setMessage("查询成功");
		return pageResult;
	}
	
	/**
	 * 
	 * <div style="color:red;font-size:18px;">周报查询</div><br>
	 * <ol>
	 * <li>按人头展示</li>
	 * <li>未写周报展示空</li>
	 * </ol>
	 * @param filter 过滤参数
	 * @return <div style="color:blue;font-size:12px;">table展示格式数据</font>
	 */
	public TableViewRspDto<WeeklyViewRspDto> weeklyList(TaskQueryFilter filter){
		log.debug("[weeklyList]查询入参：{}",filter);
		TableViewRspDto<WeeklyViewRspDto> pageResult = new TableViewRspDto<WeeklyViewRspDto>();
		if(StringUtils.isNotBlank(filter.getName())) {
			filter.setName("%"+filter.getName()+"%");
		}
		if(StringUtils.isNotBlank(filter.getCodeStartStrStart())) {
			filter.setCodeStartStrStart(filter.getCodeStartStrStart() + DateTimeConstant.TIME_OF_DAY_BEGIN);
		}
		if(StringUtils.isNotBlank(filter.getCodeEndStrEnd())) {
			filter.setCodeEndStrEnd(filter.getCodeEndStrEnd() + DateTimeConstant.TIME_OF_DAY_END);
		}
		Page<Task> page;
		if(filter.isExportFile()) {
			page = PageHelper.startPage(1, 1000);
		} else {
			page = PageHelper.startPage(filter.getPage(), filter.getLimit());
		}
		pageResult.setData(myTaskMapper.selectByFilterOrderByUser(filter));
		pageResult.setCount(page.getTotal());
		pageResult.setCode(0);
		pageResult.setMessage("查询成功");
		return pageResult;
	}
	
	/**
	 * 根据主键获取单条数据
	 * @param task 使用task对象的主键属性Id类型是Long
	 */
	public Task taskGetByPrimaryKey(Task task) {
		Task result = taskMapper.selectByPrimaryKey(task.getId());
		return result;
	}
	
	/**
	 * 根据主键更新数据
	 * @param task 被更新对象（请注意，只更新有值属性）
	 */
	public ResultBase taskUpdateByPrimaryKey(TaskUpdateItemReqDto taskUpdateItemReqDto) {
		ResultBase resultBase = new ResultBase();
		Task task = new Task();
		BeanUtils.copyProperties(taskUpdateItemReqDto, task,"updateTime","createTime");
		
		UserExample userExample = new UserExample();
		userExample.createCriteria().andIdEqualTo(taskUpdateItemReqDto.getUserId());
		List<User> userList = userMapper.selectByExample(userExample);
		task.setCoder(userList.get(0).getNick());
		task.setUpdateTime(Calendar.getInstance().getTime());
		
		//设置逻辑
		if(taskUpdateItemReqDto.getProgress() != null && taskUpdateItemReqDto.getProgress() == 100) {
			task.setStatus(TaskStatusEnum.finish);
			if(task.getCodeEnd() == null) {
				resultBase.setMessage("通过进度和状态判断任务已完成~<br>SO，请选择结束时间！");
				return resultBase;
			}
		}
		if(taskUpdateItemReqDto.getStatus() != null && taskUpdateItemReqDto.getStatus() == TaskStatusEnum.finish) {
			task.setProgress((float) 100);
			if(task.getCodeEnd() == null) {
				resultBase.setMessage("通过进度和状态判断任务已完成~<br>SO，请选择结束时间！");
				return resultBase;
			}
		}
		
		taskMapper.updateByPrimaryKey(task);
		resultBase.setSuccess(true);
		resultBase.setMessage("更新成功");
		return resultBase;
	}
	
	/**
	 * 根据主键删除数据
	 * @param keys 被删除对象主键List集合
	 */
	@Transactional
	public ResultBase taskDeleteByPrimaryKey(List<Long> keys) {
		ResultBase resultBase = new ResultBase();
		try {
			keys.forEach((key)->{
				taskMapper.deleteByPrimaryKey(key);
			});
		} catch (Exception e) {
			resultBase.setMessage(e.getMessage());
			return resultBase;
		}
		resultBase.setSuccess(true);
		resultBase.setMessage("成功删除"+keys.size()+"条记录");
		return resultBase;
	}
	
	/**
	 * 新增数据
	 * @param taskAddItemReqDto 新增对象
	 */
	@Transactional
	public ResultBase taskSave(TaskAddItemReqDto taskAddItemReqDto) {
		ResultBase resultBase = new ResultBase();
		Task task = new Task();
		BeanUtils.copyProperties(taskAddItemReqDto, task,"updateTime","createTime");
		UserExample userExample = new UserExample();
		userExample.createCriteria().andIdEqualTo(taskAddItemReqDto.getUserId());
		List<User> userList = userMapper.selectByExample(userExample);
		task.setCoder(userList.get(0).getNick());
		task.setUpdateTime(Calendar.getInstance().getTime());
		task.setCreateTime(Calendar.getInstance().getTime());
		
		//设置逻辑
		if(taskAddItemReqDto.getProgress() != null && taskAddItemReqDto.getProgress() == 100) {
			task.setStatus(TaskStatusEnum.finish);
			if(task.getCodeEnd() == null) {
				resultBase.setMessage("通过进度和状态判断任务已完成~<br>SO，请选择结束时间！");
				return resultBase;
			}
		}
		if(taskAddItemReqDto.getStatus() != null && taskAddItemReqDto.getStatus() == TaskStatusEnum.finish) {
			task.setProgress((float) 100);
			if(task.getCodeEnd() == null) {
				resultBase.setMessage("通过进度和状态判断任务已完成~<br>SO，请选择结束时间！");
				return resultBase;
			}
		}
		
		taskMapper.insertSelective(task);
		resultBase.setSuccess(true);
		resultBase.setMessage("新增成功");
		return resultBase;
	}
}
